#include "CdiRenderObjectList.h"
using namespace std;

CdiRenderObjectList::CdiRenderObjectList(void) 
: m_objects( NULL )
{
  m_objects = new list< CdiRenderBase* > ();
}

bool CdiRenderObjectList::AddObject( CdiRenderBase* object )
{
  if( m_objects ) 
  {
    m_objects->push_front( object );
    return true;
  }
  return false;
}

CdiRenderObjectList::~CdiRenderObjectList(void)
{
  if( m_objects )
  {
    // delete all the objects and clear the list
    std::list< CdiRenderBase* >::iterator objectList = m_objects->begin();
    std::list< CdiRenderBase* >::iterator endList = m_objects->end();
    for( ; objectList != endList; objectList++ )
    {
      delete (*objectList);
    }

    m_objects->clear();

    delete m_objects;
    m_objects = NULL;
  }
}

bool CdiRenderObjectList::RenderAll( LPDIRECT3DDEVICE9 pDevice )
{
  bool rendered = false;
  if( GetItemCount() > 0 && m_objects != NULL )
  {
    std::list< CdiRenderBase* >::iterator objectList = m_objects->begin();
    std::list< CdiRenderBase* >::iterator endList = m_objects->end();

    for( ; objectList != endList; objectList++ )
    {
      CdiRenderBase* base = (CdiRenderBase*)(*objectList);
      if( base->CanRender() == TRUE )
      {
        base->Render( pDevice );
      }
    }
    rendered = true;
  }
  return rendered;
}

bool CdiRenderObjectList::Render(int item, LPDIRECT3DDEVICE9 pDevice) 
{
  bool rendered = false;
  if(   (m_objects != NULL ) && 
        (item >= 0) && 
        (GetItemCount() > item ))
  {
    std::list< CdiRenderBase* >::iterator objectList = m_objects->begin();
    try 
    {
      for( int i = 0; i < item; ++i )
      {
        objectList++;
      }
      CdiRenderBase* base = (CdiRenderBase*) (*objectList);
      if(base != NULL && base->CanRender()) 
      {
        base->Render( pDevice );
      }
      rendered = true;
    } 
    catch( ... )
    {
      
    }
  }
  return rendered;
}

CdiRenderBase* CdiRenderObjectList::GetItem(int itemIndex ) 
{
  if( GetItemCount() > itemIndex )
  {
    std::list<CdiRenderBase*>::iterator objects = m_objects->begin();
    for( int i = 0; i <= itemIndex; ++i )
    {
      objects++;
    }
    return (CdiRenderBase*)(*objects);
  }
  return NULL;
}

const int CdiRenderObjectList::GetItemCount()
{
  if( m_objects != NULL )
  {
    return (const int)(m_objects->size());
  }
  return -1;
}

bool CdiRenderObjectList::RemoveObject( CdiRenderBase* object )
{
  return false;
}

bool CdiRenderObjectList::RemoveObject( int index )
{
  return false;
}